<?php
/*
 * estudo de padrões de projetos com php
 * author: fabricio s costa
 * version: 1.0
 * site: http://fabriciojf.com
 */

require_once('com/fabriciojf/persistence/PDOConnectionFactory.class.php');
require_once('com/fabriciojf/model/Post.class.php');
require_once('com/fabriciojf/include/TrataTiny.class.php');
require_once('com/fabriciojf/include/Data.class.php');
require_once('com/fabriciojf/persistence/CategoriaDAO.class.php');

class PostDAO extends PDOConnectionFactory {

    // realiza uma inserção
    public function save($post){

        try{

            $conex = PDOConnectionFactory::getConnection();

            $stmt = $conex->prepare("INSERT INTO post (titulo, conteudo, idCategoria, dataCriacao, tipo) VALUES (?, ?, ?, ?, ?)");

            $stmt->bindValue(1, $post->getTitulo());
            $stmt->bindValue(2, TrataTiny::limpaTexto($post->getConteudo()));
            $stmt->bindValue(3, $post->getCategoria()->getId());
            $stmt->bindValue(4, $post->getDataCriacao());
            $stmt->bindValue(5, $post->getTipo());

            // executo a query preparada
            $stmt->execute();

            return true;

            // caso ocorra um erro, retorna o erro;
        }catch ( PDOException $ex ){
            echo "Erro: ".$ex->getMessage();
            return false;
        }
    }

    // realiza um Update
    public function update($post){
        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->prepare("UPDATE post SET titulo=?, conteudo=?, idCategoria=?, dataCriacao=?, tipo=? WHERE id=?");
            $conex->beginTransaction();

            // valores encapsulados nas variáveis da classe Agenda.

            // sequencia de índices que representa cada valor de minha query
            $stmt->bindValue(1, $post->getTitulo());
            $stmt->bindValue(2, TrataTiny::limpaTexto($post->getConteudo()));
            $stmt->bindValue(3, $post->getCategoria()->getId());
            $stmt->bindValue(4, $post->getDataCriacao());
            $stmt->bindValue(5, $post->getTipo());
            $stmt->bindValue(6, $post->getId());

            // executo a query preparada
            $stmt->execute();
            $conex->commit();

            return true;

            // caso ocorra um erro, retorna o erro;
        } catch ( PDOException $ex ){
            echo "Erro: ".$ex->getMessage();
            return false;
        }

    }

    // remove um registro
    public function remove( $id ){

        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->exec("DELETE FROM post WHERE id=$id");

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }

    }

    public function listAllTemp($pagina, $limit){

        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post ORDER BY id DESC LIMIT $pagina,$limit");

            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }

    public function listAll($pagina, $limit){

        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post WHERE tipo = 'post' ORDER BY id DESC LIMIT $pagina,$limit");

            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {                    
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }

    public function listAllPostsInativos($pagina, $limit){

        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post WHERE tipo = 'inat' ORDER BY id DESC LIMIT $pagina,$limit");

            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }

    public function listAllPages(){

        try{
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post WHERE tipo = 'page' ORDER BY id DESC");

            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;
        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); }
    }

    public function findForId($id){

        try{

            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post WHERE id=$id");

            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }

    public function findForConteudo($pagina, $limit, $termo){

        try{
            
            $conex = PDOConnectionFactory::getConnection();
            $stmt = $conex->query("SELECT * FROM post WHERE upper(titulo) like '%".strtoupper($termo)."%' OR upper(conteudo) like '%".strtoupper($termo)."%'  LIMIT $pagina,$limit");
            
            $list = array();
            if ($stmt) {
                $rows = $stmt->fetchAll();
                $i = 0;
                foreach ($rows as $rs) {
                    $list[$i] = new Post();
                    $list[$i]->setId($rs['id']);
                    $list[$i]->setTitulo($rs['titulo']);
                    $list[$i]->setConteudo($rs['conteudo']);
                    $list[$i]->setDataCriacao(Data::formatarDataExtenso($rs['dataCriacao']));
                    $list[$i]->setTipo($rs['tipo']);
                    $i++;
                }
            }

            return $list;

        }catch ( PDOException $ex ){ echo "Erro: ".$ex->getMessage(); exit;}
    }
}
?>
